import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/pages/article/widget/item.dart';
import 'package:flutter_smart_heating/pages/basic/company/widget/item.dart';
import 'package:flutter_smart_heating/pages/basic/station/widget/item.dart';
import 'package:flutter_smart_heating/pages/search/widget/search_tabbar_view.dart';
import 'package:flutter_smart_heating/pages/user/support/widget/help_center_item_view.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

import 'logic.dart';
import 'state.dart';

class SearchPage extends StatelessWidget {
  final SearchLogic logic = Get.put(SearchLogic());
  final SearchState state = Get.find<SearchLogic>().state;

  SearchPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        titleSpacing: 0,
        leading: Container(),
        leadingWidth: UiTheme.spacingX,
        backgroundColor: UiTheme(context).match(light: Colors.white),
        title: Padding(
          padding: const EdgeInsets.symmetric(vertical: UiTheme.toolbarSpacing),
          child: UiSearchBar(
            height: 35,
            backgroundColor:
                UiTheme(context).match(light: Colors.grey.withOpacity(0.15)),
            controller: state.searchBarController,
            onSubmitted: (value) {
              logic.search(value);
            },
            onChanged: (value) {
              if (value == '') {
                logic.search(value);
              }
            },
            onClear: () {
              state.keyword = '';
              logic.fetchList();
            },
          ),
        ),
        actions: [
          SizedBox(
            height: 35,
            child: TextButton(
              style: TextButton.styleFrom(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
                ),
                padding: EdgeInsets.zero,
                splashFactory: NoSplash.splashFactory,
                foregroundColor: Colors.grey.withOpacity(0.5),
              ),
              onPressed: () {
                App.back(context);
              },
              child: Text(
                '取消',
                style: TextStyle(
                    color: UiTheme(context).match(
                  light: UiTheme.primary,
                  dark: Colors.white70,
                )),
              ),
            ),
          )
        ],
      ),
      body: KeyboardDismissOnTap(
        child: Column(
          children: [
            SearchTabbarView(state: state, logic: logic),
            const Divider(
              height: 0,
              thickness: 0.2,
            ),
            Expanded(
              child: UiLifeCycle(
                onRouteDone: () {
                  state.searchBarController.requestFocus();
                },
                child: GetBuilder<SearchLogic>(
                  id: 'result',
                  builder: (context) {
                    return state.loading
                        ? const UiLoading()
                        : state.result['list'].isEmpty
                            ? UiResult(
                                text: state.keyword == '' ? '请输入关键词' : '暂无相关结果',
                              )
                            : UiRefresher(
                                controller: state.refreshController,
                                onLoad: state.currentIndex == 0
                                    ? null
                                    : () {
                                        state.pagination.currentPage++;
                                        logic.fetchList();
                                      },
                                child: ListView.builder(
                                  padding: EdgeInsets.zero,
                                  itemCount: state.result['list'].length,
                                  itemBuilder: (context, index) {
                                    var item = state.result['list'][index];
                                    switch (state.result['type']) {
                                      case 'all':
                                        return SafeArea(
                                          top: false,
                                          bottom: index + 1 ==
                                              state.result['list'].length,
                                          child: allResultPanelView(
                                              context, item, index),
                                        );
                                      case 'basic_company':
                                        return BasicCompanyItemView(
                                          item: item,
                                          index: 0,
                                        );
                                      case 'basic_station':
                                        return BasicStationItemView(
                                          item: item,
                                          index: 0,
                                        );
                                      case 'plugin_article':
                                        return Padding(
                                          padding: EdgeInsets.only(
                                            bottom: 15,
                                            top: index == 0 ? 15 : 0,
                                            left: 15,
                                            right: 15,
                                          ),
                                          child: ArticleItemView(
                                            item: item,
                                            index: 0,
                                          ),
                                        );
                                      case 'plugin_help_center':
                                        return Padding(
                                          padding: EdgeInsets.only(
                                              top: index == 0
                                                  ? UiTheme.spacingX
                                                  : 0),
                                          child: HelpCenterItemView(item: item),
                                        );
                                    }
                                    return Container();
                                  },
                                ),
                              );
                  },
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget allResultPanelView(context, item, index) {
    return UiPanel(
      backgroundColor: UiTheme.of(context).match(light: Colors.white),
      margin: const EdgeInsets.only(
          left: UiTheme.spacingXX,
          right: UiTheme.spacingXX,
          top: UiTheme.spacingX),
      children: [
        UiListCell(
          onTap: () {
            state.tabController.index = state.category
                .indexWhere((element) => element['type'] == item['type']);
            logic.onTabsClick(state.tabController.index);
          },
          backgroundColor: UiTheme(context).panelBackground,
          title: Text(
            '${item["title"]}(${item['total']})',
            style: const TextStyle(
              fontWeight: FontWeight.bold,
            ),
          ),
          trailing: const Text('更多', style: TextStyle(fontSize: 14)),
          padding: const EdgeInsets.symmetric(horizontal: 20),
          showArrow: true,
          showDivider: true,
        ),
        Column(
          children: List.generate(item['list'].length, (index) {
            var row = item['list'][index];
            switch (item['type']) {
              case 'plugin_help_center':
                return HelpCenterItemView(item: row);
              case 'basic_company':
                return Padding(
                  padding: const EdgeInsets.only(bottom: 15),
                  child: BasicCompanyItemView(
                    item: row,
                    index: index,
                  ),
                );
              case 'basic_station':
                return Padding(
                  padding: const EdgeInsets.only(bottom: 15),
                  child: BasicStationItemView(
                    item: row,
                    index: index,
                  ),
                );
              case 'plugin_article':
                return Padding(
                  padding: EdgeInsets.only(
                    bottom: 15,
                    top: index == 0 ? 15 : 0,
                    left: 15,
                    right: 15,
                  ),
                  child: ArticleItemView(
                    item: row,
                    index: index,
                  ),
                );
            }
            return Container();
          }),
        )
      ],
    );
  }
}
